<template>
  <div class="pagebox">
    <div class="leftBox bg">
      <div class="btnBox" v-for="(item, index) in buttonLists" :key="index" :style="{ height: menuHeight }">
        <a-button :type="item.active" block @click="axleHandle(item, index)">
          {{ item.label }}
        </a-button>
      </div>
    </div>
    <div class="rightBox bg">
      <div style="text-align: right;">
        <a-button type="primary" v-if="isStartBtnShow" @click="beginCollection">开始</a-button>
        <a-button type="danger" v-if="!isStartBtnShow" @click="stopCollection">暂停</a-button>
      </div>
      <div class="chartBox">
        <NormalLine :lineData="chartOption"></NormalLine>
      </div>
    </div>
  </div>
</template>
<script>
function mqttSend(publishTopic, subscribeTopic, payload, _this) {
  let qos = 2;
  let { client } = _this;
  client.publish(publishTopic, JSON.stringify(payload), qos);
  client.subscribe(subscribeTopic);
}

// Generate four random hex digits.
function S4() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

// Generate a pseudo-GUID by concatenating random hexadecimal.
function guid() {
  return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
}

function intervalLists(lists, interval) {
  return lists.filter((item, index) => index % interval == 0);
}

function bufferLists(recLists, lists) {
  let _recLists = [];
  if (recLists.length > 100) {
    _recLists = recLists.splice(lists.length);
    _recLists = _recLists.concat(lists);
  } else {
    _recLists = recLists.concat(lists);
  }
  return _recLists;
}

function bufferXAxis(lineNumbers, xAxisLists) {
  let end = '';
  if (xAxisLists.length > 0) {
    end = xAxisLists[xAxisLists.length - 1];
  } else {
    end = 0;
  }
  return lineNumbers.map((item, index) => (JSON.parse(end) + index * 0.1).toFixed(2));
}

function bufferSeriesLists(recLists, lists) {
  let _recLists = [];
  if (recLists.length > 0) {
    _recLists = recLists.map((item, index) => {
      let { data, ...rest } = item;
      let _data = [];
      if (data.length > 100) {
        _data = data.splice(lists[index].data.length);
        _data = _data.concat(lists[index].data);
      } else {
        _data = data.concat(lists[index].data);
      }
      return {
        data: _data,
        ...rest,
      };
    });
  } else {
    _recLists = recLists.concat(lists);
  }
  return _recLists;
}

function parseModelData(object) {
  let modelFile = {};
  buildObj(object, modelFile);
  console.log(modelFile);
  return Object.values(modelFile);

  function buildObj(object, modelFile) {
    let { id, name, type, description, ids } = object;
    modelFile[id] = { id, name, type, ids: ids || '', description: description || '' };
    for (const key in object) {
      if (Object.hasOwnProperty.call(object, key)) {
        if (Array.isArray(object[key])) {
          object[key].forEach((item) => {
            buildObj(item, modelFile);
          });
        }
      }
    }
  }
}

let colorList = ['#FF3535', '#FF7865', '#FFBB00', '#f8d77e'];
import varibless from '@assets/styles/varibless.less';
import api from '@/api/deviceInfo.js';
import Paho from 'paho-mqtt';
import NormalLine from './component/normalLine.vue';

export default {
  data() {
    return {
      menuHeight: '',
      varibless: varibless,
      macsn: '', // 测试 1E3A3F5AF4908EA
      clientId: `client-hzsk-${guid()}`,
      MQTToption: {},
      client: {},
      timer: '',
      modelFileDataLists: [],
      channelDatalists: [],
      pageSelectedLists: [],
      selectedGroupLists: [],
      recLineNumbers: [],
      recXAxisLists: [],
      recSeriesLists: [],
      groupId: 0,
      buttonLists: [],
      isStartBtnShow: false,
      chartOption: {},
    };
  },
  components: {
    NormalLine,
  },
  methods: {
    beginCollection() {
      this.client.connect({ onSuccess: this.onConnect, keepAliveInterval: 30 });
      this.isStartBtnShow = !this.isStartBtnShow;
    },

    stopCollection() {
      this.client.disconnect();
      this.isStartBtnShow = !this.isStartBtnShow;
    },

    // 选择采样数据轴
    axleHandle(item, index) {
      let _this = this;

      this.groupId = index;

      this.buttonLists.forEach((item, index) => {
        item.active = index == this.groupId ? 'primary' : '';
      });

      this.isStartBtnShow = true;
      this.recXAxisLists = [];
      this.recSeriesLists = [];
      this.client.disconnect();

      this.chartOption = {
        legendDataLists: [],
        lineNumberDataLists: [],
        xAxisDataLists: [],
        seriesDataLists: [
          { data: [] },
          { data: [] },
          { data: [] },
          { data: [] },
          { data: [] },
          { data: [] },
          { data: [] },
        ],
      };
    },

    // called when the client loses its connection
    onConnectionLost(responseObject) {
      let _this = this;
      console.log('------------------onConnectionLost');
      console.log(responseObject);
      let { errorCode } = responseObject;

      switch (errorCode) {
        case 0:
          // _this.chartOption = {
          //   legendDataLists: [],
          //   lineNumberDataLists: [],
          //   xAxisDataLists: [],
          //   seriesDataLists: [
          //     { data: [] },
          //     { data: [] },
          //     { data: [] },
          //     { data: [] },
          //     { data: [] },
          //     { data: [] },
          //     { data: [] },
          //   ],
          // };
          break;
        case 8:
          // _this.$confirm('长时间无操作与服务器连接断开,请点击确认按钮,重新连接', '连接超时', {
          //   confirmButtonText: '确定',
          //   callback: (action) => {
          //     _this.client.connect({ onSuccess: this.onConnect, timeout: 180 });
          //   },
          // });
          _this.$warning({
            title: '连接超时',
            content: '长时间无操作与服务器连接断开',
          });
          break;
        default:
          break;
      }
    },
    // called when a message arrives
    onMessageArrived(message) {
      console.log('------------------onMessageArrived');
      console.log(message);
      let _this = this;
      let { payloadString } = message;
      let messageReceive = JSON.parse(payloadString);
      let subscribeTopic = `Sample/${this.macsn}/sample_channel1`;

      if (messageReceive.code == 'OK') {
        // Sample/1E3A3F5AF4908EA/sample_channel1
        console.log(messageReceive);
        let { probe } = messageReceive;
        this.modelFileDataLists = parseModelData(probe);
        this.channelDatalists = this.modelFileDataLists.find((item) => item.id == 'sample_channel1').ids;
        this.client.subscribe(subscribeTopic);
      } else if (messageReceive.id != '') {
        // 通过采集通道获取的数据
        let { data } = messageReceive;
        // 通过模型文件数据和采集通道获取的数据进行合并,需要展示的数据都要从channelDatalists获取
        console.log('------------------ReceiveData', data);
        // debugger
        this.channelDatalists = this.channelDatalists.map((item, index) => {
          let ele = _this.modelFileDataLists.find((obj) => item.id == obj.id);
          return {
            ...ele,
            dataLists: data[index].data,
          };
        });

        this.initChart();

        let lineNumbers = [];
        let xAxisLists = [];
        let seriesLists = [];
        let legendLists = [];

        // this.selectedGroupLists = this.pageSelectedLists.find((item, index) => index == this.groupId).group;
        this.selectedGroupLists = this.pageSelectedLists.find((item, index) => index == this.groupId).group;

        legendLists = this.selectedGroupLists.map((item, index) => {
          return item.name;
        });

        lineNumbers = this.channelDatalists.find((item) => item.type == 'LINE_NUMBER').dataLists;
        // xAxisLists = this.channelDatalists.find((item) => item.type == 'LINE_NUMBER').dataLists;

        seriesLists = this.selectedGroupLists.map((item) => {
          let { name, dataLists } = item;
          return {
            name,
            type: 'line',
            smooth: true,
            symbol: 'none',
            data: dataLists,
          };
        });

        // console.log(seriesLists);
        this.recLineNumbers = bufferLists(this.recLineNumbers, lineNumbers);
        this.recXAxisLists = bufferXAxis(this.recLineNumbers, this.recXAxisLists);
        this.recSeriesLists = bufferSeriesLists(this.recSeriesLists, seriesLists);

        this.chartOption = {
          legendDataLists: legendLists,
          lineNumberDataLists: lineNumbers,
          xAxisDataLists: this.recXAxisLists,
          seriesDataLists: this.recSeriesLists,
        };
      }
    },
    onConnect() {
      let _this = this;
      // let payload = {
      //   equipment: _this.macsn,
      //   type: 'dir',
      //   dirPath: `${_this.dirPath}/log`,
      //   guid: _this.clientId,
      // };
      let { publishTopic, subscribeTopic } = _this.MQTToption;
      mqttSend(publishTopic, subscribeTopic, {}, _this);
    },

    initChart() {
      // 获取模型数据中的轴
      let axisLists = [];
      axisLists = this.modelFileDataLists.filter((item) => item.type == 'AXIS' || item.id == '01035437');
      // 通过轴找到与轴有关的数据
      this.pageSelectedLists = axisLists.map((item) => {
        let group = [];
        this.channelDatalists.forEach((obj) => {
          if (obj.id.indexOf(item.id) > -1) {
            group.push(obj);
          }
        });
        return {
          group,
          ...item,
        };
      });
      // 获取按钮列表
      this.buttonLists = axisLists.map((item, index) => {
        let { name, id } = item;
        return {
          label: name,
          value: index,
          active: index == this.groupId ? 'primary' : '',
        };
      });
    },
  },
  mounted() {
    let _this = this;
    let MQTToption = {
      url: this.$mqttUrl,
      clientId: this.clientId,
      timeout: 10 * 1000,
      keepAliveInterval: 10,
      cleanSession: false,
      ssl: false,
      diviceID: 'macsn',
      publishTopic: `Probe/Query/Request/${this.macsn}`,
      subscribeTopic: `Probe/Query/Response/${this.macsn}`,
    };
    this.MQTToption = MQTToption;

    let { url, clientId, publishTopic, subscribeTopic } = MQTToption;

    let client = new Paho.Client(url, clientId);

    this.client = client;
    // set callback handlers
    client.onConnectionLost = this.onConnectionLost;
    client.onMessageArrived = this.onMessageArrived;

    
    // connect the client
    client.connect({
      onSuccess: this.onConnect,
      keepAliveInterval: 30,
    });
  },
  created() {
    let _this = this;
    // this.macsn = '1E3A3F5AF4908EA';
    this.macsn = this.$route.query.macsn;

    this.menuHeight = document.body.clientHeight - this.varibless.headerHeightpxno + 'px';
    window.onresize = function() {
      // 定义窗口大小变更通知事件
      _this.menuHeight = document.documentElement.clientHeight - _this.varibless.headerHeightpxno + 'px';
    };
  },
  destroyed() {
    // clearInterval(this.timer);
    this.client.disconnect();
  },
};
</script>
<style scoped lang="less">
@import './index.less';
.pagebox {
  width: 100%;
  height: 100%;
}

.leftBox {
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
  background-color: #fff;
  margin-bottom: 16px;
}

.rightBox {
  width: 100%;
  padding: 4px 8px;
  background-color: #fff;
}

.btnBox {
  padding: 4px;
  background-color: #fff;
}

.chartBox {
  width: 100%;
  height: 600px;
}
</style>
